package com.generic.dao.impl;

import java.util.List;

import org.hibernate.Query;

import com.generic.dao.ModuleDao;
import com.generic.ds.HibernateSession;
import com.generic.module.impl.Image;

public class ImageDao extends ModuleDao {
	
	private static final int MAX = 0;
	private static final int MIN = 1;
	
	public ImageDao(HibernateSession session) {
		super(session, Image.class);
	}
	
	@SuppressWarnings("unchecked")
	public List<Image> getImages(Long profileId) {
//		StringBuffer sb = new StringBuffer("select");
//		sb.append(" Id");
//		sb.append(", concat('/").append(Constant.IMAGE_THUMB_PATH).append(profileId).append("/',File_Name)");
//		sb.append(", concat('/").append(Constant.IMAGE_PATH).append(profileId).append("/',File_Name)");
//		sb.append(", Caption");
//		sb.append(" from Image");
//		sb.append(" where Profile_Id = :profileId");
//		sb.append(" order by Created_Date");
		StringBuffer sb = new StringBuffer("from Image");
		sb.append(" where Profile_Id = :profileId");
		sb.append(" order by Seq");
		
		Query query = dsSession.createQuery(sb.toString());
		query.setLong("profileId", profileId);
		
		return (List<Image>)query.list();
	}
	
	public Integer getSeq(Long profileId, Long albumId) {
		StringBuffer sb = new StringBuffer("select");
		sb.append(" max(Seq)");	
		sb.append(" from Image");
		sb.append(" where Profile_id = :profileId");
		sb.append(" and Profile_id = :albumId");
		
		Query query = dsSession.createSQLQuery(sb.toString());
		query.setLong("profileId", profileId);
		query.setLong("albumId", albumId);
		
		Object seq = query.uniqueResult();
		if(seq != null) {
			return Integer.parseInt(seq.toString());
		}
		return 0;
	}
	
	public Long getMaxId(Long profileId) {
		return getId(MAX, profileId);
	}
	
	public Long getMinId(Long profileId) {
		return getId(MIN, profileId);
	}
	
	private Long getId(int type, Long profileId) {
		StringBuffer sb = new StringBuffer("select");
		if(type == MAX) {
			sb.append(" max(id)");
		} else {
			sb.append(" min(id)");
		}		
		sb.append(" from Image");
		sb.append(" where profile_id = :profileId");
		
		Query query = dsSession.createSQLQuery(sb.toString());
		query.setLong("profileId", profileId);
		
		Object id = query.uniqueResult();
		if(id != null) {
			return Long.parseLong(id.toString());
		} else {
			return 0l;
		}
	}
}
